package summer.codegenerator.model.base;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ModelUtils {


    public static Set<Long> ids(List models) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Set<Long> ids = new HashSet<>();
        if(!CollectionUtils.isEmpty(models)) {

            Map<Class<?>, Method> clazzAndIdMethod = new HashMap<>();
            for(Object model : models) {
                Class<?> modelClazz = model.getClass();
                Method modelIdGetMethod = clazzAndIdMethod.get(modelClazz);
                if(modelIdGetMethod == null) {
                    for(Field field : modelClazz.getDeclaredFields()) {
                        if(field.isAnnotationPresent(Id.class)) {
                            clazzAndIdMethod.put(modelClazz, modelIdGetMethod);
                            modelIdGetMethod = modelClazz.getDeclaredMethod("get" +
                                    StringUtils.capitalize(field.getName()));
                            break;
                        }
                    }
                }
                if(modelIdGetMethod != null) {
                    ids.add((Long) modelIdGetMethod.invoke(model));
                }
            }
        }
        return ids;
    }
}
